<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>授权测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-result { margin: 10px 0; padding: 10px; border-radius: 5px; }
        .success { background-color: #d4edda; color: #155724; }
        .error { background-color: #f8d7da; color: #721c24; }
        button { margin: 5px; padding: 10px 15px; }
    </style>
</head>
<body>
    <h1>API授权测试</h1>
    
    <div>
        <h3>当前Token状态:</h3>
        <div id="token-status"></div>
    </div>
    
    <div>
        <h3>测试操作:</h3>
        <button onclick="testMyScales()">测试获取我的量表</button>
        <button onclick="testAnalytics()">测试分析数据</button>
        <button onclick="clearToken()">清除Token</button>
        <button onclick="setTestToken()">设置测试Token</button>
    </div>
    
    <div id="test-results"></div>

    <script>
        // 检查Token状态
        function checkTokenStatus() {
            const token = localStorage.getItem('userToken');
            const statusDiv = document.getElementById('token-status');
            
            if (token) {
                statusDiv.innerHTML = `<div class="test-result success">Token存在: ${token.substring(0, 20)}...</div>`;
            } else {
                statusDiv.innerHTML = `<div class="test-result error">Token不存在</div>`;
            }
        }
        
        // 通用API请求函数（复制自base.html）
        function apiRequest(url, options = {}) {
            const userToken = localStorage.getItem('userToken');
            if (!userToken) {
                return Promise.reject(new Error('No token'));
            }

            const defaultHeaders = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + userToken
            };

            options.headers = { ...defaultHeaders, ...(options.headers || {}) };

            return fetch(url, options)
                .then(response => {
                    if (response.status === 401) {
                        throw new Error('Unauthorized');
                    }
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    return response.json();
                })
                .catch(error => {
                    throw error;
                });
        }
        
        // 测试获取我的量表
        function testMyScales() {
            addResult('正在测试获取我的量表...', 'info');
            
            apiRequest('/api/scales/my')
                .then(response => {
                    if (response.success) {
                        addResult(`成功获取量表数据: ${response.data.scales.length} 个量表`, 'success');
                    } else {
                        addResult(`获取失败: ${response.message}`, 'error');
                    }
                })
                .catch(error => {
                    addResult(`请求失败: ${error.message}`, 'error');
                });
        }
        
        // 测试分析数据
        function testAnalytics() {
            addResult('正在测试分析数据...', 'info');
            
            // 先获取量表列表，然后测试分析接口
            apiRequest('/api/scales/my')
                .then(response => {
                    if (response.success && response.data.scales.length > 0) {
                        const scaleId = response.data.scales[0].id;
                        return apiRequest(`/api/scales/${scaleId}/analytics`);
                    } else {
                        throw new Error('没有可用的量表进行测试');
                    }
                })
                .then(response => {
                    if (response.success) {
                        addResult('成功获取分析数据', 'success');
                    } else {
                        addResult(`获取分析数据失败: ${response.message}`, 'error');
                    }
                })
                .catch(error => {
                    addResult(`分析数据请求失败: ${error.message}`, 'error');
                });
        }
        
        // 清除Token
        function clearToken() {
            localStorage.removeItem('userToken');
            addResult('Token已清除', 'success');
            checkTokenStatus();
        }
        
        // 设置测试Token
        function setTestToken() {
            const testToken = 'test_token_' + Date.now();
            localStorage.setItem('userToken', testToken);
            addResult('已设置测试Token', 'success');
            checkTokenStatus();
        }
        
        // 添加测试结果
        function addResult(message, type) {
            const resultsDiv = document.getElementById('test-results');
            const resultDiv = document.createElement('div');
            resultDiv.className = `test-result ${type}`;
            resultDiv.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            resultsDiv.appendChild(resultDiv);
        }
        
        // 页面加载时检查Token状态
        window.addEventListener('load', checkTokenStatus);
    </script>
</body>
</html>